<script setup>
import {ref, onMounted, computed} from 'vue';
import ComAffix from "@/components/ComAffix.vue";
import {ElUpload, ElIcon, ElMessage, ElForm} from 'element-plus';
import {Key} from '@element-plus/icons-vue';
import {Avatar, HomeFilled, Setting, User} from '@element-plus/icons-vue';
import {
  userGetUserInfoService,
  updateUserInfoService,
} from '@/api/user.js';
import {useUserStore} from "@/stores/index.js";
import useFileUpload from "@/utiles/common.js";

// 状态管理
const useStore = useUserStore();
const formRef = ref(null);
const loading = ref(false);

// 表单数据
const form = ref({
  nickname: useStore.user.nickname || '',
  phone: useStore.user.phone || '',
  introduced: useStore.user.introduced || '',
  avatar: useStore.user.avatar || ''
});

// 头像URL（从store中实时获取）
const avatarUrl = computed(() => useStore.user.avatar);

// 表单验证规则
const rules = ref({
  nickname: [
    {required: true, message: '昵称不能为空', trigger: 'blur'},
    {min: 2, max: 20, message: '昵称长度在2-20个字符之间', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '手机号不能为空', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ]
});

// 组件挂载时初始化数据
onMounted(async () => {
  try {
    if (!useStore.user.id) {
      const response = await userGetUserInfoService();
      useStore.setUser(response.data);
    }

    // 同步store数据到表单
    form.value = {
      nickname: useStore.user.nickname,
      phone: useStore.user.phone,
      introduced: useStore.user.introduced,
      avatar: useStore.user.avatar
    };
  } catch (error) {
    ElMessage.error('获取用户信息失败，请稍后重试');
    console.error(error);
  }
});

// 头像上传配置
const coverUpload = useFileUpload({
  endpoint: 'http://localhost:8081/common/upload',
  extraData: {type: 'avatar'}, // 明确指定是头像上传
  maxSize: 2 * 1024 * 1024,
  allowedTypes: ['image/jpeg', 'image/png', 'image/jpg']
});

// 上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片格式！');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！');
    return false;
  }
  return true;
};

// 自定义头像上传逻辑（核心功能）
const customUpload = async (options) => {
  try {
    // 1. 获取上传的文件
    const file = options.file;

    // 2. 执行上传前校验
    if (!beforeAvatarUpload(file)) {
      options.onError(new Error('文件校验失败'));
      return;
    }

    // 3. 调用上传工具上传文件
    const uploadResult = await coverUpload.upload(file);
    const avatarUrl = uploadResult.url || uploadResult; // 兼容不同返回格式

    // 4. 更新表单和全局状态
    form.value.avatar = avatarUrl;
    useStore.setUser({
      ...useStore.user,
      avatar: avatarUrl
    });

    // 5. 通知上传组件成功并提示
    options.onSuccess();
    ElMessage.success('头像上传成功');
    console.log('新头像URL：', avatarUrl);
  } catch (error) {
    options.onError(error);
    ElMessage.error('头像上传失败，请稍后重试');
    console.error('上传错误：', error);
  }
};

// 保存用户信息
const saveUserInfo = async () => {
  try {
    loading.value = true;

    // 1. 验证用户ID
    const userId = useStore.user.id;
    if (!userId) {
      ElMessage.error('未获取到用户ID，无法更新');
      return;
    }

    // 2. 准备更新数据
    const updateData = {
      nickname: form.value.nickname,
      phone: form.value.phone,
      introduced: form.value.introduced,
      avatar: form.value.avatar // 包含最新头像URL
    };

    // 3. 调用API更新
    const updatedUser = await updateUserInfoService(userId, updateData);
    console.log(updatedUser)
    // 4. 更新全局状态
    useStore.setUser(updatedUser.data.data);

    ElMessage.success('个人信息更新成功');
  } catch (error) {
    ElMessage.error('更新失败，请稍后重试');
    console.error('更新错误：', error);
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div class="main">
    <el-affix :offset="0">
      <ComAffix/>
    </el-affix>
    <div class="bode">
      <div class="page">
        <div class="side">
          <div class="message-title">
            <el-icon>
              <Setting/>
            </el-icon>
            <span class="center">账号设置</span>
          </div>

          <el-menu default-active="3" router>
            <el-menu-item index="/set">
              <template #title>
                <el-icon>
                  <Avatar/>
                </el-icon>
                <span>个人中心</span>
              </template>
            </el-menu-item>

            <el-menu-item index="/user">
              <template #title>
                <el-icon>
                  <HomeFilled/>
                </el-icon>
                <span>个人主页</span>
              </template>
            </el-menu-item>

            <el-menu-item index="/safe">
              <template #title>
                <el-icon>
                  <Key/>
                </el-icon>
                <span>密码设置</span>
              </template>
            </el-menu-item>
          </el-menu>
        </div>
        <div class="change-avatar">
          <!-- 头像上传区域 - 使用store中的头像 -->
          <div class="avatar-section">
            <div class="vis">
              <el-row class="avatar-row">
                <el-col :span="24" class="avatar-col">
                  <el-upload
                    class="avatar-uploader"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :http-request="customUpload"
                    :action="''"
                  >
                    <!-- 关键：v-if 和 v-else 写在相邻位置，中间无其他元素 -->
                    <img v-if="avatarUrl" :src="avatarUrl" class="avatar-img"/>
                    <el-icon v-else class="avatar-placeholder"><User/></el-icon>
                  </el-upload>
                </el-col>
              </el-row>
            </div>
            <p class="avatar-desc">点击头像更换</p>
          </div>

          <!-- 用户信息编辑区域 -->
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="80px"
            class="info-form"
          >
            <!-- 昵称输入框 -->
            <el-form-item label="昵称" prop="nickname">
              <el-input
                v-model="form.nickname"
                clearable
                :maxlength="20"
              />
            </el-form-item>

            <!-- 手机号输入框 -->
            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="form.phone"
                clearable
                :maxlength="11"
              />
            </el-form-item>

            <!-- 个性签名输入框 -->
            <el-form-item label="个性签名">
              <el-input
                v-model="form.introduced"
                clearable
                :maxlength="100"
                type="textarea"
                :rows="2"
              />
              <div class="ebutton">
              <el-button
                type="primary"
                class="save-btn"
                @click="saveUserInfo"
                :loading="loading"
              >
                保存信息
              </el-button>
              </div>
            </el-form-item>

            <!-- 保存按钮 -->

          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">

.bode {
  display: grid;
  margin-top: 40px;
  justify-content: center;
  background-color: #f6f3f3;
}

.page {
  background-color: white;
  display: flex;
  justify-content: center;
  width: 100%; /* 占满父容器 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);

  .side {
    flex: 0 0 20%; /* 占 30% 宽度 */
  }

  .change-avatar {
    flex: 1; /* 占剩余 70% 宽度 */
    display: grid;
    width: 800px;
    height: 500px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  }
}

.el-menu {
  border-right: none;
  background-color: transparent;

  .el-menu-item {
    height: 56px;
    line-height: 56px;
    border-top: none;
    border-left: 3px solid transparent;
    transition: all 0.2s ease;

    &:hover {
      background-color: #d1def3;
      border-left-color: #a2bac9;
    }

    &.is-active {
      background-color: #f5f7fa;
      border-left-color: #409eff;
      color: #409eff;

      .el-icon {
        color: #409eff;
      }
    }

    .el-icon {
      font-size: 16px;
      margin-right: 12px;
      color: #faccd1;
    }
  }
}
// 账号设置标题样式（带图标和文字排版）
.message-title {
  // 布局与对齐
  display: flex;
  align-items: center;
  padding: 18px 24px; // 上下内边距稍大，增强区域感
  gap: 12px; // 图标与文字间距

  // 图标样式
  .el-icon {
    font-size: 20px; // 图标尺寸适中
    color: #409eff; // 主题色图标，突出标题
    width: 24px;
    height: 24px;
    flex-shrink: 0; // 防止图标被压缩
  }

  // 文字样式
  .center {
    font-size: 18px;
    font-weight: 500; // 中等加粗，突出层级
    color: #303133; // 深灰色文字，提升可读性
    line-height: 1.4;
  }

  // 装饰与分隔
  border-bottom: 1px solid #f0f0f0; // 底部浅色边框，分隔区域
  background-color: #fcfcfc; // 轻微背景色，与内容区区分
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02); // 顶部微阴影，增强层次感
}

// 响应式适配
@media (max-width: 768px) {
  .message-title {
    padding: 14px 16px; // 小屏幕减少内边距
    gap: 10px;

    .el-icon {
      font-size: 18px;
    }

    .center {
      font-size: 16px;
    }
  }
}
.center {
  font-size: 20px;
}

.text {
  font-size: 14px;
}

.box-card {
  width: 480px;
}

.badge-container {
  position: relative;
}

span {
  justify-content: center;
  display: flex;
}
.avatar-section{
  display: grid;
  justify-content: center;
  margin-left: 40px;
  margin-top: 30px;
}
// 头像区域样式
.change-avatar {
  width:500px;
  display: flex;
  justify-content: center; // 头像居中显示

}
.vis {
  width: 120px;
  height: 120px;
  border-radius: 50%; /* 圆形容器 */
  overflow: hidden; /* 裁剪超出圆形的部分 */
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer; /* 鼠标悬停显示手型，提示可点击 */
  border: 2px solid #eee; /* 轻微边框，增强视觉效果 */

  // 适配 el-row
  .avatar-row {
    width: 100%;
    height: 100%;
    margin: 0 !important; /* 强制清除 el-row 自带的 margin */
    padding: 0;
    box-sizing: border-box;
    .avatar-placeholder {
      font-size: 40px;      // 设置图标大小
      color: #ffffff;       // 设置图标颜色（Element Plus 灰色）
      display: flex;        // 弹性布局
      justify-content: center; // 水平居中
      align-items: center;   // 垂直居中
      width: 100%;          // 占满容器宽度
      height: 100%;         // 占满容器高度
    }

    // 适配 el-col（栅格列）
    .avatar-col {
      width: 100%;
      height: 100%;
      padding: 0 !important; /* 清除 el-col 自带的 padding */
      margin: 0;
    }

    // 头像图片样式（核心贴合样式）
    .avatar-img {
      position: absolute; /* 脱离文档流，便于完全覆盖 */
      top: 0;
      left: 0;
      width: 100%; /* 宽度填满容器 */
      height: 100%; /* 高度填满容器 */
      object-fit: cover; /* 核心：按比例缩放，填满容器，裁剪多余部分 */
      object-position: center; /* 图片居中显示（优先展示中心区域） */
    }
    .avatar-desc {
      margin-top: 10px;
      color: #666;
      font-size: 14px;
    }
  }
  .ebutton{
    margin-top: 10px;
  }
}

</style>
